<!-- Bot Read Me -->
<!-- Author: Edwin -->
<template>
  <div>
    <el-dialog :close-on-press-escape="false"
               :close-on-click-modal="false"
               :visible.sync="visible"
               append-to-body
               width="920px"
               top="100px"
               class="cui-custom-css-bot-edit">
      <div slot="title"
           class="header-title">
        <span class="title-name">{{!dataForm.id ? $t('custom.bots.edit.titleAdd') : $t('custom.bots.edit.titleEdit')}}</span>
        <view-linked-info :linkKey="'createNewBotwiki'"></view-linked-info>
      </div>
      <div class="area">
        <div class="action">
          <el-tabs tab-position="left">
            <el-tab-pane v-if="$hasPermission('sys:bots:bot:from:blank')">
              <div slot="label"
                   class="template_label">
                <div>Start From Blank</div>
                <p>Starting from blank lets you create a totally custom flow to meet your needs.</p>
              </div>
              <div class="scroll-content scroll-css">
                <div class="card-list"
                     v-loading="temLoading">
                  <div v-for="(item, index) in triangleOptions"
                       :key="index"
                       @click="selectScriptOrTemplate(item, 'script')"
                       :class="{'card-border':item.id===stateObj['scriptId']}"
                       class="card-list-item">
                    <div class="image">
                      <el-image style="width: 100%;height: 100%;"
                                :src="item.icon?item.icon:triggerImgUrl[index]"></el-image>
                    </div>
                    <div v-if="comWidthIsOverflow(item.name, 'name')"
                         class="name">{{ item.name }}</div>
                    <el-tooltip :open-delay="1000"
                                v-else
                                effect="dark"
                                :content="item.name"
                                placement="bottom-start">
                      <div class="name">
                        {{ item.name }}
                      </div>
                    </el-tooltip>
                    <div v-if="comWidthIsOverflow(item.description, 'description')"
                         class="description">{{ item.description }}</div>
                    <el-tooltip :open-delay="1000"
                                v-else
                                effect="dark"
                                :content="item.description"
                                placement="bottom-start">
                      <div class="description">
                        {{ item.description }}
                      </div>
                    </el-tooltip>
                  </div>
                </div>
              </div>
            </el-tab-pane>
            <!-- <el-tab-pane v-if="$hasPermission('sys:bots:bot:from:type')">
              <div slot="label"
                   class="template_label">
                <div>Start From Bot Type</div>
                <p>Pre-made templates make this an easier way to start, plus you can add customizations.</p>
              </div>
              <div class="card-list scroll-css">
                <div v-for="(item, index) in templatesList"
                     :key="index"
                     @click="selectScriptOrTemplate(item, 'template')"
                     :class="{'card-border':item.id===stateObj['id']}"
                     class="card-list-item"
                     v-if="item.type !== 100101">
                  <div class="image">
                    <el-image style="width: 100%;height: 100%;"
                              :src="item.icon?item.icon:$ossLink+'/app/bot/bot-icon-normal.png'"></el-image>
                  </div>
                  <div>
                    <div v-if="comWidthIsOverflow(item.name, 'name')"
                         class="name">{{ item.name }}</div>
                    <el-tooltip :open-delay="1000"
                                v-else
                                effect="dark"
                                :content="item.name"
                                placement="bottom-start">
                      <div class="name">
                        {{ item.name }}
                      </div>
                    </el-tooltip>
                    <div v-if="comWidthIsOverflow(item.description, 'description')"
                         class="description">{{ item.description }}</div>
                    <el-tooltip :open-delay="1000"
                                v-else
                                effect="dark"
                                :content="item.description"
                                placement="bottom-start">
                      <div class="description">
                        {{ item.description }}
                      </div>
                    </el-tooltip>
                  </div>
                </div>
              </div>
            </el-tab-pane> -->
            <el-tab-pane v-if="$hasPermission('sys:bots:bot:store')"
                         :class="'bot_store_tempalte'">
              <div slot="label"
                   class="template_label">
                <div>Start From Bot Template</div>
                <p>Fully functional bots make this the easiest way to start, plus you still can add customizations.</p>
              </div>
              <el-tabs v-model="activeName"
                       @tab-click="handleClick">
                       <el-tab-pane :label="item.name" :name="item.code" v-for="(item,index) in integrations" :key="index">
                        <div v-loading="temTabloading">
                          <botStoreTempalte  v-if="templateTabData.length>0"
                            @createbotTem="receiveBotStore"
                            :templateStoreList="templateTabData"
                            :stateObj="stateObj"></botStoreTempalte>
                            <template v-else>
                              <ZEmpty :image="`${$ossLink}/app/view_pageheader/dataset_nodate.png`"
                                      description="No bot found"
                                      style="margin-top: 150px;"
                                      >
                              </ZEmpty>
                            </template>

                        </div>                    
                      </el-tab-pane>

                <!-- <el-tab-pane label="Top Picks"
                             name="first">
                  <botStoreTempalte @botStoreTem="receiveBotStore"
                                    :templateStoreList="templateStoreList"
                                    :stateObj="stateObj"></botStoreTempalte>
                </el-tab-pane>
                <el-tab-pane label="Remote work"
                             name="second">Remote work</el-tab-pane>
                <el-tab-pane label="Email"
                             name="third">Email</el-tab-pane>
                <el-tab-pane label="Notifications"
                             name="fourths">Notifications</el-tab-pane>
                <el-tab-pane label="Save to cloud"
                             name="fourthss">Save to cloud</el-tab-pane>
                <el-tab-pane label="Approval"
                             name="fourthsss">Approval</el-tab-pane> -->
              </el-tabs>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
      <el-dialog :visible.sync="moreEditVisible"
                 :title="$t('custom.reports.moreedit')"
                 :close-on-click-modal="false"
                 :close-on-press-escape="false"
                 :modal='false'
                 style="margin-top:-16px"
                 width="545px">
        <div class="screen-y scroll-css"
             style="height:557px;">
          <el-form :model="dataForm"
                   style="padding:0 20px"
                   ref="moreEditDataForm"
                   :rules="FormRules"
                   label-position="top">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item prop="businessType"
                              :label="$t('custom.dataset.businessType')">
                  <el-select v-model="dataForm.businessType"
                             :placeholder="$t('custom.dataset.businessType')"
                             style="width: 100%;"
                             :disabled="!$hasPermission('sys:tenant:model:allowtomanagesystemmodel')">
                    <el-option v-for="its in businessTypeList"
                               :key="its.dictValue"
                               :label="its.dictLabel"
                               :value="its.dictValue"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <!-- <span>{{dataForm}}</span> -->
                <el-form-item prop="tenantCode"
                              placeholder="Client"
                              :label="$t('custom.dataset.tenantCode')">
                  <select-client-id v-model="dataForm.tenantCode"
                                    :disabled="dataForm.businessType==='Template' || dataForm.businessType==='MSPbots Internal'"
                                    :width="100"></select-client-id>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="status"
                              :label="$t('custom.dataset.status')">
                  <el-select v-model="dataForm.status"
                             :placeholder="$t('custom.dataset.status')"
                             style="width: 100%;"
                             :disabled="!$hasPermission('sys:tenant:model:allowtomanagesystemmodel')">
                    <el-option v-for="its in statusList"
                               :key="its.dictValue"
                               :label="its.dictLabel"
                               :value="its.dictValue"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="11">
                <el-form-item prop="owner"
                              :label="$t('custom.report.owner')"
                              v-if="$hasPermission('sys:report:owner')">
                  <el-select v-model="dataForm.owner"
                            clearable
                            filterable
                            :placeholder="$t('custom.report.owner')"
                            style="width: 100%;">
                    <el-option v-for="its in userList"
                              :key="its.id"
                              :label="its.realName"
                              :value="its.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="22">
                <el-form-item prop="progress"
                              :label="$t('custom.reports.progress')">
                  <el-input v-model="dataForm.progress"
                            :placeholder="$t('custom.reports.progress')"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item prop="eta"
                              :label="$t('custom.reports.eta')">
                  <el-date-picker v-model="dataForm.eta"
                                  type="date"
                                  style="width: 100%;"
                                  :label="$t('custom.reports.eta')">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item prop="priority"
                              :label="$t('custom.reports.priority')"
                              class="right-margin">
                  <el-select v-model="dataForm.priority"
                            :placeholder="$t('custom.reports.priority')"
                            :disabled='false'
                            style="width: 100%;">
                    <el-option label="High"
                              value="High"></el-option>
                    <el-option label="Medium"
                              value="Medium"></el-option>
                    <el-option label="Low"
                              value="Low"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="22">
                <el-form-item prop="client"
                              :label="$t('custom.reports.client')">
                  <el-input v-model="dataForm.client"
                            @keyup.enter.native.stop
                            type="textarea"
                            rows="2"
                            :placeholder="$t('custom.reports.client')"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item prop="uat"
                              :label="$t('custom.reports.uat')">
                  <el-select v-model="dataForm.uat"
                            :disabled='false'
                            :placeholder="$t('custom.reports.uat')"
                            style="width: 100%;">
                    <el-option v-for="its in uatList"
                              :key="its.value"
                              :label="its.lable"
                              :value="its.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item prop="overheadFilters"
                              :label="$t('custom.reports.overheadFilters')"
                              class="right-margin">
                  <el-select v-model="dataForm.overheadFilters"
                            :disabled='false'
                            :placeholder="$t('custom.reports.overheadFilters')"
                            style="width: 100%;">
                    <el-option v-for="its in optionList"
                              :key="its.value"
                              :label="its.lable"
                              :value="its.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item prop="reportingQa"
                              :label="$t('custom.reports.reportingQa')">
                  <el-select v-model="dataForm.reportingQa"
                            :disabled='false'
                            :placeholder="$t('custom.reports.reportingQa')"
                            style="width: 100%;">
                    <el-option v-for="its in optionList"
                              :key="its.value"
                              :label="its.lable"
                              :value="its.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item prop="allClientsQa"
                              :label="$t('custom.reports.allClientsQa')"
                              class="right-margin">
                  <el-select v-model="dataForm.allClientsQa"
                            :disabled='false'
                            :placeholder="$t('custom.reports.allClientsQa')"
                            style="width: 100%;">
                    <el-option v-for="its in optionList"
                              :key="its.value"
                              :label="its.lable"
                              :value="its.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="22">
                <el-form-item prop="internalNotes"
                              :label="$t('custom.reports.internalNotes')">
                  <el-input v-model="dataForm.internalNotes"
                            @keyup.enter.native.stop
                            type="textarea"
                            rows="2"
                            :placeholder="$t('custom.reports.internalNotes')"></el-input>
                </el-form-item>
              </el-col> -->
            </el-row>

          </el-form>
        </div>
        <!-- <template slot="footer">
          <el-button @click="moreEditVisible = false"
                    size="small">{{ $t('Cancel') }}</el-button>
          <el-button type="primary"
                    size="small"
                    @click="dataFormSubmitHandle()">{{ $t('Save') }}</el-button>
        </template> -->
      </el-dialog>
    </el-dialog>
  </div>
</template>
<script>
// import getFlowSetting from './TruggerTemplate'
import botStoreTempalte from './bot-store-template'
import {fetchBotTemplates,checkBotName,fetchBot,fetchIntegration,fetchBotList} from '@/api/new'
import {  values, get } from 'lodash'
import ZEmpty from '@/components/storybook/z-empty'

export default {
  components: { botStoreTempalte,ZEmpty },
  data () {
    return {
      input2: '',
      visible: false,
      loading: false,
      temLoading: false,
      submitBtnLoading: false,
      stateObj: -1,
      editEmptyBot: false,
      dataForm: {
        id: this.$route.query.botId,
        name: null,
        integration: null,
        description: null,
        businessType: '',
        tenantCode: this.$store.state.user.tenantCode,
        status: ''
      },
      integrationList: [],
      triangleOptions: [],
      triggerImgUrl: [
        'https://us.flow.microsoft.com/Content/retail/assets/scheduledCard.66b44d1c1967f652f7a5734b82e127ec.2.svg',
        'https://us.flow.microsoft.com/Content/retail/assets/instantCard.712e68fa8273fff7fa5ee2bf5e6b6fd7.2.svg',
        'https://us.flow.microsoft.com/Content/retail/assets/automatedCard.3145b0aff51761bc7685f5fcc4104355.2.svg',
        'https://us.flow.microsoft.com/Content/retail/assets/uiFlowCard.0e38415014af5cf1423e6e99791b526b.2.svg',
        'https://us.flow.microsoft.com/Content/retail/assets/bpfCard.405428c580d33a66cbca1de80a343334.2.svg'
      ],
      templatesList: [],
      templateStoreList: [],
      templateList: [],
      templateTabData: [],
      tempNumber: 0,
      moreEditVisible: false,
      activeName: '',
      integrations:[],
      temTabloading:false
    }
  },
  computed: {
    businessTypeList () {
      try {
        if (this.$hasPermission('sys:widget:type:mspbots internal') && this.$route.path.includes('CrossTenant')) {
          return window.SITE_CONFIG['dictList'].find(e => e.dictType === 'datasets_type_list').dataList.filter(item => {
            return item.dictValue === 'MSPbots Internal'
          })
        } else {
          return window.SITE_CONFIG['dictList'].find(e => e.dictType === 'datasets_type_list').dataList.filter(item => {
            return item.dictValue !== 'MSPbots Internal'
          })
        }
      } catch (error) {
        return []
      }
    },
    statusList () {
      try {
        var list = window.SITE_CONFIG['dictList'].find(e => e.dictType === 'datasets_status_list').dataList
        if (this.$hasPermission('sys:widget:publishauth')) {
          return list
        } else {
          return this._.reject(this._.reject(list, { dictValue: 'Alpha' }), { dictValue: 'Published' })
        }
      } catch (error) {
        return []
      }
    },
    dataFormRules () {
      return {
        name: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur', pattern: '[^ \x22]+' },
          { required: true, message: this.$t('custom.tips.required', { fields: 'Name' }), trigger: 'blur' },
          { validator: this.validatePass, trigger: 'blur' }
        ],
        description: [
          { required: false, message: this.$t('custom.tips.required', { fields: 'Description' }), trigger: 'blur' }
        ]
      }
    },
    FormRules () {
      return {
        businessType: [
          { required: false, message: this.$t('custom.tips.required', { fields: 'Type' }), trigger: 'change' }
        ],
        tenantCode: [
          { required: false, message: this.$t('custom.tips.required', { fields: 'Client' }), trigger: 'change' }
        ],
        status: [
          { required: false, message: this.$t('custom.tips.required', { fields: 'Status' }), trigger: 'change' }
        ]
      }
    },
    canEditModel () {
      return Boolean(!this.dataForm.id || this.editEmptyBot)
    },
    isStartFromTemplate () {
      return Boolean(typeof this.stateObj === 'object' && this.stateObj['type'] !== 'trigger')
    },
    comDialogTop () {
      return window.innerHeight > 688 ? (window.innerHeight - 688) / 2 : 20
    }
  },
  methods: {
    handleClick (tab, event) {
     this.templateTabData = this.templateList.filter(item=>{
         if(item.integrationList.length>0){
            return item.integrationList.some(e=>e.code===tab.name)
        }
      })   
    },
    async getTemBotData () {
      try {
        const params = {
          businessType:"Template",
          resourceType: 4,
          disable: true,
          internal: false,
          filter: {
              type: ["Template"]
          },
          order: [
              {
                  sort: "DESC",
                  field: "update_date"
              }
          ],
          showAllIntegration: false,
          integrationGroup: [ ],
          size: 9999,
          current: 1
        }
        this.temTabloading = true
         const {data: response} = await fetchBotList(params)
          if (response.code !== 0) {
           throw response.msg
         }
         this.templateList = response.data.records || []
         let arr = []
          this.templateList.forEach(item=>{
           arr = arr.concat(item.integrationList)
          })
          this.integrations = this._.uniqBy(arr, 'code').sort((a, b) => (get(a, 'name') || '').charCodeAt(0) - (get(b, 'name') || '').charCodeAt(0)) || []

         this.temTabloading = false
      } catch (error) {
        this.templateList = []
        this.integrations = []
        this.temTabloading = false
        
      }
        
    },
    validatePass (rule, value, callback) {
      let params = {
        name: this.dataForm.name,
        id: this.dataForm.id ? this.dataForm.id : ''
      }
      checkBotName(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return callback(new Error(res.msg))
          }
          callback()
        })
    },
    botsMoreEdit () {
      this.moreEditVisible = true
    },
    validateClick () {
      if (this.canEditModel) {
        return true
      } else {
        this.$message.warning('This mode does not support modifying Start from blank. Please carefully select the Start from blank you need when adding.')
        return false
      }
    },
    init () {
      this.visible = true
      this.$nextTick(() => {
        if (this.dataForm.id || this.$route.query.botId) {
          this.getInfo()
        }
        // this.getTemplateList()
        // this.getBotStoreList()
        // this.getIntegrations()
        this.getTemBotData().then(()=>{
          this.activeName = this.integrations[0].code
          let tab = this.integrations[0]
          tab.name = tab.code
          this.handleClick(tab)
        })
        this.getTriggerList()

      })
    },
     getIntegrations () {
          const params = {
          tenantCode: this.$store.state.user.tenantCode,
          loadType: 3
        }
        fetchIntegration(params).then(({ data: response })=>{
          if (response.code !== 0) {
          throw response.msg
         }
        const integrations = response.data || {}
        this.integrations = values(integrations).sort((a, b) => (get(a, 'name') || '').charCodeAt(0) - (get(b, 'name') || '').charCodeAt(0))
        this.integrations = this.integrations.filter((item) => Number(get(item, 'sync.group')) < 2)
        this.integrations.push({
          name:'No Integration',
          sync:{
            subjectCode:'No Integration'
          } 
        })
        }).catch((err)=>{
          this.integrations = []
        })
    },
    getInfo () {
      const _this = this
      this.loading = true
      const params = {
        id: this.dataForm.id
      }
      fetchBot(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return _this.$message.error(res.msg)
          }
          _this.dataForm = {
            ..._this.dataForm,
            ...res.data
          }
          _this.dataForm.tenantCode = _this.dataForm.tenantCode || this.$store.state.user.tenantCode
          _this.editEmptyBot = false
          // if (res.data.sysBotScriptList.length > 0) {
          //   _this.stateObj = res.data.sysBotScriptList[0]
          // } else {
          //   _this.editEmptyBot = true
          // }
          if (res.data.originalId) {
            _this.setDefaultStateObj(res.data.originalId)
          }

          _this.loading = false
        }).catch(() => {
        })
    },
    setDefaultStateObj (originalId) {
      this.tempNumber++
      if (this.templatesList.length > 0) {
        this.stateObj = this.templatesList.find(e => e.id === originalId)
        this.dataForm.integration = this.stateObj.integration
        this.tempNumber = 0
      } else if (this.tempNumber < 10) {
        setTimeout(() => {
          this.setDefaultStateObj(originalId)
        }, 1000)
      }
    },
    canceldialog () {
      this.visible = false
      // this.$emit('refreshList')
    },
    getIntegrationList () {
      const params = {
        tenantCode: this.$store.state.user.tenantCode,
        loadType: 3
      }
      return this.$interface.taskManager.getConnectorInfoNew(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          let mapObj = res.data
          let tempList = []
          for (let key in mapObj) {
            tempList.push({
              name: mapObj[key].name,
              subjectCode: mapObj[key].sync.subjectCode,
              status: mapObj[key].sync.status
            })
          }
          this.integrationList = tempList
        })
        .catch(() => { })
    },
    async getTriggerList () {
      this.temLoading = true
      const { data: res } = await this.$interface.bots.getBotsListApi({ type: 'trigger', enable: true })
      if (res.code === 0) {
        this.triangleOptions = res.data
      }
      this.temLoading = false
    },
    getBotStoreList () {
      this.$interface.bots.getBotsStoreListApi()
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.templateStoreList = res.data
        })
    },
    getTemplateList () {
      fetchBotTemplates()
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.templatesList = res.data
        })
    },
    selectScriptOrTemplate (item, type) {
      this.visible = false
      let classification = ''
      if (this.validateClick()) {
        if (type === 'script') {
          this.stateObj = item
          this.stateObj['scriptId'] = item.id
          classification = 'Quality Assurance Bot'
        }
        if (type === 'template') {
          // if (this.stateObj['id'] === item.id) {
          //   this.stateObj = -1
          // } else {
          this.stateObj = item
          this.stateObj['id'] = item.id
          this.dataForm.integration = item.integration
          // }
        }
        if (type === 'Store') {
          this.stateObj = item
          this.stateObj['scriptId'] = item.id
        }
        this.stateObj.classification = item.classification
      }
      this.$store.commit('BOTTEMPLATETYPE', type)
      this.$store.commit('BOTFORMEDIT', false)
      this.$emit('showDataForm', { item: item, type: type, classification: classification })
    },
    receiveBotStore (params) {
      this.selectScriptOrTemplate(params.item, params.type)
    },
    comWidthIsOverflow (str, type) {
      if (!str) {
        return true
      }
      if (type === 'name') {
        if (str.length <= 15) {
          return true
        } else {
          return false
        }
      }
      if (type === 'description') {
        if (str.length <= 50) {
          return true
        } else {
          return false
        }
      }
      return false
    }
  }
}
</script>

<style lang="scss" scoped>
@import "src/views/modules/mspbots/bots-bak/my-bots/add-or-update";
.card-border {
  box-shadow: 0px 0px 8px 0px #229aea !important;
}
.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #606266;
}
</style>
<style lang="scss">
.cui-custom-css-bot-edit {
  .el-dialog__header {
    box-shadow: 0px 1px 0px 0px #f0f0f0;
  }
  .el-dialog__body {
    padding: 0;
  }
  .el-form-item {
    margin-bottom: 10px;
  }
}
</style>
